package fun.ticsmyc.multiThread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Ticsmyc
 * @package fun.ticsmyc.multiThread
 * @date 2020-08-16 11:52
 */
class ShareData{
    private Lock lock  = new ReentrantLock();
    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();
    private int count =1;

    public void printA(){
        lock.lock();

        try{
            while(count ==1){
                c2.await();
            }
            System.out.println(Thread.currentThread().getName()+"\t2");
            count=1;
            c1.signal();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            lock.unlock();
        }
    }

    public void printB(){
        lock.lock();

        try{
            while(count ==2){
                c1.await();
            }
            System.out.println(Thread.currentThread().getName()+"\t1");
            count=2;
            c2.signal();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            lock.unlock();
        }
    }

}
public class 两个线程轮流调用 {

    public static void main(String[] args) {
        ShareData shareData = new ShareData();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                shareData.printA();
            }
        }).start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                shareData.printB();
            }
        }).start();
    }
}
